package com.anlu.cloud.log.autoconfigure;

import com.anlu.cloud.log.Log;
import com.anlu.cloud.log.contants.LogQueue;
import com.anlu.cloud.user.LoginAppUser;
import com.anlu.cloud.utils.AppUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 *  通过mq发送日志<br>
 */
public class LogMQClient {
    private static final Logger logger = LoggerFactory.getLogger(LogMQClient.class);

    private AmqpTemplate amqpTemplate;

    public LogMQClient(AmqpTemplate amqpTemplate) {
        this.amqpTemplate = amqpTemplate;
    }

    /**
     * 发送日志信息
     * @param module
     * @param username
     * @param params
     * @param remark
     * @param flag
     */
    public void sendLogMsg(String module, String username, String params, String remark, boolean flag) {
        CompletableFuture.runAsync(()->{
                try{
                    Log log = new Log();
                    log.setCreateTime(new Date());
                    if(StringUtils.isNotBlank(username)){
                        log.setUsername(username);
                    }else{
                        LoginAppUser loginAppUser = AppUserUtils.getLoginAppUser();
                        if(loginAppUser!=null){
                            log.setUsername(loginAppUser.getUsername());
                        }
                    }
                    log.setFlag(flag);
                    log.setModule(module);
                    log.setParams(params);
                    log.setRemark(remark);

                    amqpTemplate.convertAndSend(LogQueue.LOG_QUEUE, log);
                    logger.info("发送日志到队列：{}", log);
                }catch (Exception e){
                    e.printStackTrace();
                }
        });

    }


    }
